<template>
  <div class="app-container customer-div">
    <!--数据列表-->
    <div class="table-container">
      <vxe-grid ref='xGrid' v-bind="gridOptions" size="mini" :loading="listLoading"  @checkbox-change="checkboxChange" @checkbox-all="selectAllCheckboxChange">
        <template #form>
          <!--搜索-->
          <div>
            <div style="background: #f5f7fa;padding:15px 15px 0 15px;border:1px solid #EBEEF5;border-bottom:0.5px solid #EBEEF5;">
              <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
                <el-form-item label="搜索内容：">
                  <el-input v-model="listQuery.keywords" placeholder="品类/厂家/牌号" clearable></el-input>
                </el-form-item>
                <el-form-item label="采购员：">
                  <el-select v-model="listQuery.chargeUserId" filterable placeholder="请选择" clearable>
                    <el-option
                      v-for="item in userOptionList"
                      :key="item.userId"
                      :label="item.userName"
                      :value="item.userId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="更新时间：">
                  <el-date-picker
                    v-model="listQuery.scoreDate"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button
                    @click="handleSearchList()"
                    type="primary">
                    查询
                  </el-button>
                  <el-button
                    v-if="purchaseGoodsScore"
                    @click="batchEdit()"
                    type="primary">
                    批量编辑
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </template>
        <template #pager>
          <div style="overflow: hidden">
            <div class="pagination-container" style="float:right;">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize"
                :page-sizes="[10,15,20,50,100,200]"
                :total="count">
              </el-pagination>
            </div>
          </div>
        </template>

        <template #toolbar_buttons>
          <el-radio-group v-model="listQuery.className" size="small"  @change="handleSearchList">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in goodsPriceCategoryLists" :label="item"  :key="index">{{ item }}</el-radio-button>
          </el-radio-group>
        </template>

        <template #num4_default="{ row, rowIndex }">
          <el-button  v-if="purchaseGoodsScore && row.chargeUserId == userId" type="text" size="small" @click="showEdit('one',row)">编辑</el-button>
          <el-button  v-if="saleGoodsScore" type="text" size="small" @click="showPf(row)">评分</el-button>
          <el-button  type="text" size="small" @click="showChart(row)">趋势</el-button>
        </template>
      </vxe-grid>
    </div>
    <!--采购编辑-->
    <el-dialog
      :before-close="handleClose"
      title="编辑产品竞争力&推荐值"
      :visible.sync="dialogVisible"
      width="420px">
      <div style="padding-bottom: 10px;text-align: center" v-if="popType=='one'">请填写本产品的竞争力&推荐值</div>
      <el-form :model="pumsForm" size="mini" label-width="100px" ref="pumsForm" :rules="rules">
        <el-form-item label="产品名称：" style="margin-bottom:5px" v-if="popType=='one'">{{goodsName}}</el-form-item>
        <el-form-item label="竞争力：" prop="purchaseCompetitive">
          <el-input-number v-model="pumsForm.purchaseCompetitive" controls-position="right"  :min="1" :max="100"></el-input-number>
          <span style="font-size: 12px;color:#888;padding-left:5px">最小值为1，最大值100</span>
        </el-form-item>
        <el-form-item label="推荐值：" prop="purchaseScore">
          <div style="padding-top:4px" >
            <el-rate v-model="pumsForm.purchaseScore"></el-rate>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!--销售评分-->
    <el-dialog
      :before-close="handleClose2"
      :close-on-click-modal="false"
      title="产品评分"
      :visible.sync="dialogVisible2"
      width="420px">
      <div style="padding-bottom: 10px;text-align: center">请填写你认为的产品评分</div>
      <el-form :model="saleForm" size="mini" label-width="100px" ref="saleForm" :rules="rules2">
        <el-form-item label="产品名称：" style="margin-bottom:5px">{{goodsName}}</el-form-item>
        <el-form-item label="评分：" prop="saleCompetitive">
          <el-input-number v-model="saleForm.saleCompetitive" controls-position="right"  :min="1" :max="100"></el-input-number>
          <span style="font-size: 12px;color:#888;padding-left:5px">最小值为1，最大值100</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>

    <!--趋势-->
    <el-dialog
      title="产品趋势"
      :visible.sync="dialogVisible3"
      width="600px">
      <div id="myChart" :style="{'height':'400px'}" v-loading="loadingChart"></div>
    </el-dialog>

  </div>
</template>

<script>

import {goodsScoreList,purchaseEditScore,saleEditScore,scoreListByGoods} from '@/api/allInLine/goods'
import {goodsPriceCategoryList} from '@/api/allInLine/inquiry'
import {getOrderUsersList} from '@/api/partner'
import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
import { Message } from 'element-ui';

const defaultListQuery={
  pageNum: 1,
  pageSize: 10,
  keywords : "", //关键词搜索(品类、厂家、牌号)
  chargeUserId : '', //采购号ID
  scoreDate : [], //更新时间
  className:''
};

const defaultPumsForm = {
  sapGoodsId:'',
  purchaseScore:undefined,
  purchaseCompetitive:undefined
}
const defaultSaleForm = {
  sapGoodsId:'',
  saleCompetitive:undefined,
}

export default {
  name: "index",
  data(){
    return{
      roles:store.getters.roles ? store.getters.roles : [],
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      count:0,
      listLoading:false,
      loading:false,
      goodsPriceCategoryLists:[],
      userOptionList:[],
      type:1,
      gridOptions:{
        loading:this.listLoading,
        border: true,
        id: 'competitive',
        align:'center',
        autoResize:true,
        height:800,
        size:'mini',
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          }
        },
        columns: [
          { type: 'checkbox',
            title: '',
            width: 50,
          },
          {
            field: 'className',
            title: '品类',
            minwidth: 150,

          },
          {
            field: 'brandName',
            title: '厂家',
            minwidth: 150,
          },
          {
            field: 'goodsSn',
            title: '牌号',
            minwidth: 150,
          },
          {
            field: 'chargeUserName',
            title: '采购员',
            minwidth: 100,
          },
          {
            field: 'purchaseCompetitive',
            title: '竞争力',
            minwidth: 100,
          },
          {
            field: 'purchaseScore',
            title: '推荐值',
            minwidth: 100,
          },
          {
            field: 'scoreDate',
            title: '更新日期',
            minwidth: 150,
          },
          {
            field: 'saleCompetitive',
            title: '销售评分',
            minwidth: 100,
          },
          {
            field: 'setting',
            title: '操作',
            width: 150,
            fixed:'right',
            slots: {
              // 使用 JSX 渲染
              default: 'num4_default',
            },
          },
        ],
        data:[{}],
      },
      records:[],
      dialogVisible:false,
      btnLoading:false,
      pumsForm:JSON.parse(JSON.stringify(defaultPumsForm)),
      popType:'',
      rules:{
        purchaseCompetitive:[{required: true, message: '此项必填', trigger: 'change'},],
        purchaseScore:[{required: true, message: '此项必填', trigger: 'blur'},],
      },


      dialogVisible2:false,
      btnLoading2:false,
      saleForm:JSON.parse(JSON.stringify(defaultSaleForm)),
      rules2:{
        saleCompetitive:[{required: true, message: '此项必填', trigger: 'change'},],
      },
      dialogVisible3:false,
      loadingChart:false,
      goodsName : ''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    purchaseGoodsScore() {
      if(this.roles.indexOf("purchaseGoodsScore") != -1){
        return true
      }else{
        return false
      }
    },
    saleGoodsScore() {
      if(this.roles.indexOf("saleGoodsScore") != -1){
        return true
      }else{
        return false
      }
    },
  },
  components : {

  },
  created() {
    this.getListData();
    this.getUserOptionList()
    this.getGoodsPriceCategoryList()
  },
  filters: {

  },
  methods: {
    showChart(item){
      this.dialogVisible3 = true
      scoreListByGoods({sapGoodsId:item.sapGoodsId}).then((res)=>{
        this.$nextTick(()=>{
          this.drawCaiGouCount(res.purchaseScoreList,res.purchaseCompetitiveList,res.dateList)
        })
      })


    },
    //画图表
    drawCaiGouCount(y1,y2,x){
      let myChart = this.$echarts.init(document.getElementById('myChart'));
      // 绘制图表
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['推荐值', '竞争力']
        },
        xAxis: [
          {
            type: 'category',
            data: x,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: {
            type: 'value',
          },

        series: [
          {
            name: '推荐值',
            type: 'line',
            smooth: true,
            data: y1,
          },

          {
            name: '竞争力',
            type: 'line',
            smooth: true,
            data: y2,
          },
        ]
      });
      this.loadingChart = false;
    },

    showEdit(type,item){
      this.popType = type
      this.goodsName = ''
      this.dialogVisible = true
      this.$nextTick(()=>{
        this.pumsForm = JSON.parse(JSON.stringify(defaultPumsForm))
        this.$refs.pumsForm.clearValidate()
        if(type == 'one'){
          this.pumsForm.sapGoodsId = item.sapGoodsId
          this.goodsName = item.className + '/'  + item.goodsSn
        }else{
          this.pumsForm.sapGoodsId = item.map((ee) => ee.sapGoodsId);
          this.pumsForm.sapGoodsId = this.pumsForm.sapGoodsId.join(',')
        }
      })
    },
    batchEdit(){
      if(this.records.length == 0 ){
        Message.error('请选择需要编辑的产品！')
        return false
      }
      this.showEdit('more',this.records)
    },
    handleClose(){
      this.dialogVisible = false
    },
    handleConfirm(){
      this.$refs.pumsForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.pumsForm));
          purchaseEditScore(data).then((res)=>{
            this.btnLoading = false;
            this.$refs.xGrid.clearCheckboxRow()
            this.records=[]
            this.handleClose();
            this.getListData();
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      })
    },

    showPf(item){
      this.saleForm = JSON.parse(JSON.stringify(defaultSaleForm))
      this.saleForm.sapGoodsId = item.sapGoodsId
      this.goodsName = item.className + '/' + item.goodsSn
      this.dialogVisible2 = true
      this.$nextTick(()=>{
        this.$refs.saleForm.clearValidate()
      })
    },

    handleClose2(){
      this.dialogVisible2 = false
    },
    handleConfirm2(){
      this.$refs.saleForm.validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          let data = JSON.parse(JSON.stringify(this.saleForm));
          saleEditScore(data).then((res)=>{
            this.btnLoading2 = false;
            this.handleClose2();
            this.getListData();
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      })
    },

    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList().then((res)=>{
        this.userOptionList = res;
      })
    },

    checkboxChange(checked){
      this.records = this.$refs.xGrid.getCheckboxRecords()
    },
    selectAllCheckboxChange(checked) {
      this.records = checked.records
    },

    // 获取商品报价分类列表
    getGoodsPriceCategoryList(){
      goodsPriceCategoryList().then(res=>{
        this.goodsPriceCategoryLists = res
      })
    },


    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.$refs.xGrid.clearCheckboxRow()
      this.records=[]
      this.getListData();
    },




    //获取列表
    getListData(){
      this.listLoading = true;
      let data = JSON.parse(JSON.stringify(this.listQuery));
      goodsScoreList(data).then((res)=>{
        this.gridOptions.data = res.list;
        this.count = res.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      })
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.$refs.xGrid.clearCheckboxRow()
      this.records=[]
      this.getListData();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.$refs.xGrid.clearCheckboxRow()
      this.records=[]
      this.getListData();
    },

  },
}
</script>

<style scoped lang="scss">

</style>
